//
//  TRTextField.m
//  iOSBaseFramework
//
//  Created by user on 2020/6/17.
//  Copyright © 2020 com.taylor. All rights reserved.
//

#import "TRTextField.h"

@interface TRTextField()
@property (nonatomic, assign)NSInteger tlrLength;
@end

@implementation TRTextField

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:)) //禁止黏贴
        return NO;
    if (action == @selector(select:)) //禁止选择
        return NO;
    if (action == @selector(selectAll:)) //禁止全选
        return NO;
    
    return [super canPerformAction:action withSender:sender];
}


- (instancetype) init{
    self = [super init];
    if (self) {
        
    }
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

#pragma mark - 属性的GET和SET方法

- (TRTextInputMode)inputMode{
    NSString *lang = [self.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])
        return TRTextInputModeZh_Hans;
    else if ([lang isEqualToString:@"en-US"])
        return TRTextInputMOdeEn_Us;
    return TRTextFieldModeOther;
}


- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
    _placeholderFont = placeholderFont;
    [self setValue:placeholderFont forKey:@"_placeholderLabel.font"];
}

- (void)setPlaceholderColor:(UIFont *)placeholderColor
{
    _placeholderColor = placeholderColor;
    [self setValue:placeholderColor forKey:@"_placeholderLabel.textColor"];
}

- (NSInteger)trueLength{
    UITextRange *selectedRange = [self markedTextRange];
    UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
    if (!position)
        self.tlrLength = self.text.length;
    return self.tlrLength;
}


- (void)setMaxLength:(NSInteger)maxLength
{
    if (maxLength > 0 && _maxLength == 0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tlrTextFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self
         ];
    } else if(maxLength <= 0) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    _maxLength = maxLength;
}

- (void)tlrTextFiledEditChanged:(NSNotification *)obj {
    TRTextField *textField = (TRTextField *)obj.object;
    if (textField.trueLength > textField.maxLength) {
        textField.text = [textField.text substringFromIndex:textField.maxLength];
    }
}



@end
